//
// Created by WenDaojiang on 15/11/22.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "HybridImagePickerAction.h"
#import "FZEasyFile.h"
#import "URLSessionManager.h"

@interface HybridImagePickerAction()

@property (strong, atomic) NSMutableDictionary *options;

@property (strong, atomic) NSURLSessionUploadTask *uploadTask;
@property (strong, atomic) NSURLSession *session;

@end

@implementation HybridImagePickerAction

- (void)selectImages:(id)params {

    self.options = [params mutableCopy];

    if (!_options[@"quality"]){
        _options[@"quality"] = @80;
    }

    if (!_options[@"quality"] || [_options[@"quality"] class] == [NSNumber class]){
        [self callback:NO data:@"参数 'quality' 错误!"];
        return;
    }

    if (!params[@"sourceType"] || [params[@"sourceType"] class] == [NSNumber class]){
        //self.callback(NO, @"参数 'sourceType' 错误!");
        [self callback:NO data:@"参数 'sourceType' 错误!"];
        return;
    }

    if (params[@"upload"] && [params[@"upload"] boolValue]){
        if(!params[@"uploadFormAction"] || !params[@"uploadFormName"]){
            //self.callback(NO, @"上传地址与表单字段名不能为空!");
            [self callback:NO data:@"上传地址与表单字段名不能为空!"];
            return;
        }
    }

    if (params[@"sourceType"]){
        UIImagePickerControllerSourceType sourceType = (UIImagePickerControllerSourceType) [params[@"sourceType"] integerValue];

        if([UIImagePickerController isSourceTypeAvailable:sourceType]){
            [self openImagePickerWithSourceType:sourceType];
            return;
        }
    }

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        [self showUIAlertAction];
    }else{
        [self openImagePickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
}

- (void) showUIAlertAction{

    if ([UIAlertController class]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:_options[@"title"] message:_options[@"message"] preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *actionPhotosAlbum = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self openImagePickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        }];

        UIAlertAction *actionCamera = [UIAlertAction actionWithTitle:@"摄像头" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self openImagePickerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        }];

        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            //self.callback(NO, @"用户取消了操作");
            [self callback:NO data:@"用户取消了操作"];
        }];

        [alertController addAction:actionPhotosAlbum];
        [alertController addAction:actionCamera];

        [alertController addAction:actionCancel];
        [self.controller presentViewController:alertController animated:YES completion:nil];
    }else{
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:_options[@"title"]
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles: @"相册", @"摄像头", nil];
        [actionSheet showInView:self.controller.view];
    }
}

// 打开系统图片选择窗口
- (void) openImagePickerWithSourceType:(UIImagePickerControllerSourceType) sourceType{

    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = sourceType;
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = [_options[@"editing"] boolValue];
    [self.controller presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    switch (buttonIndex){
        case 0:
            [self openImagePickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            break;
        case 1:
            [self openImagePickerWithSourceType:UIImagePickerControllerSourceTypeCamera];
            break;
        default:
            [self callback:NO data:@"用户取消了操作"];
            break;
    }
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    NSLog(@"didFinishPickingImage %@", image);

    //UIImage *image = editingInfo[@"UIImagePickerControllerOriginalImage"];
    NSURL *url = editingInfo[@"UIImagePickerControllerReferenceURL"];

    [self saveImage:image URL:url Quality:[_options[@"quality"] integerValue]];

    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //NSLog(@"didFinishPickingMediaWithInfo %@, %@", info, info[@"UIImagePickerControllerReferenceURL"]);
    UIImage *image = info[@"UIImagePickerControllerEditedImage"];
    if (!image){
        image = info[@"UIImagePickerControllerOriginalImage"];
    }
    NSURL *url = info[@"UIImagePickerControllerReferenceURL"];

    [self saveImage:image URL:url Quality:[_options[@"quality"] integerValue]];

    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 用户取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    /*if (self.callback){
        self.callback(NO, @"用户取消了操作");
    }*/
    [self callback:NO data:@"用户取消了操作"];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 保存或上传

- (void) saveImage: (UIImage *)image URL:(NSURL *)url Quality:(NSInteger)quality{

    NSData *data = nil;
    NSString *ext = @"jpg";
    if ([[url.pathExtension lowercaseString] isEqualToString:@"jpg"]){
        data = UIImageJPEGRepresentation(image, (CGFloat) (quality / 100.00));
    }else{
        data = UIImagePNGRepresentation(image);
        ext = @"png";
    }

    if([_options[@"upload"] boolValue]){
        [self uploadImage:data];
    }else{
        NSString *filePath = [NSString stringWithFormat:@"Images/%@.%@", [NSUUID UUID].UUIDString, ext];
        [FZEasyFile writeFile:filePath contents:data append:NO];

        [self callback:YES data:@{
                @"url": [@"file://" stringByAppendingString:[FZEasyFile fullFileName:filePath]],
                @"path": [FZEasyFile fullFileName:filePath],
                @"width": @(image.size.width),
                @"height": @(image.size.height),
        }];
    }
}

// 图片上传

- (void) uploadImage: (NSData *)imageData{
    NSString *url = _options[@"uploadFormAction"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.controller.view animated:YES];
    hud.labelText = @"上传中...";
    URLSessionManager *manager = [URLSessionManager defaultManager];
    [manager setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
        NSLog(@".....%lli %lli", bytesSent, totalBytesSent);
    }];
    NSProgress *progress = [NSProgress progressWithTotalUnitCount:imageData.length];
    [[manager uploadTaskWithRequest:request fromData:imageData progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [hud hide:YES];
        if(error){
            NSLog(@"- %@", error);
            [self callback:NO data: error.localizedDescription];
        } else{
            NSLog(@"- %@  %@",  response, responseObject);
            [self callback:YES data:responseObject];
        }
    }] resume];
    [progress addObserver:self forKeyPath:@"fractionCompleted" options:0 context:nil];
    [progress addObserver:self forKeyPath:@"completedUnitCount" options:0 context:nil];
    //[progress resume];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"%@", keyPath);
}


@end